import json

from flask import jsonify, session
import hashlib
import psutil
import platform
from app.utils import System
from app.utils import File
import json


def get_cpu_brand():
    if platform.system() == 'Windows':
        return platform.processor()
    elif platform.system() == 'Linux':
        with open('/proc/cpuinfo', 'r') as f:
            for line in f:
                if line.strip().startswith('model name'):
                    return line.split(':')[1].strip()
    return 'Unknown'


def service(path, cfg, data,   request):
    if path == "post/login":
        print(data)
        print(cfg)

        data = data.decode('utf-8')
        data = json.loads(data)
        if data["username"] in cfg:
            # 登录用户名正确
            # print(hashlib.sha256(data["pw"].encode()).hexdigest())
            if hashlib.sha256(data["pw"].encode()).hexdigest() == cfg[data["username"]]:
                # 密码正确
                session['username'] = data["username"]
                session['pw'] = hashlib.sha256(data["pw"].encode()).hexdigest()
                return jsonify({'code': 200, 'msg': 'Login successful'})
            else:
                return jsonify({'code': 401, 'msg': 'Wrong password'})
        else:
            return jsonify({'code': 404, 'msg': 'User not found'})
    elif path == "get/runtime_state":
        # 获取CPU信息
        cpu_count = psutil.cpu_count()
        cpu_percent = psutil.cpu_percent(interval=1)

        # 获取内存信息
        memory_info = psutil.virtual_memory()
        total_memory = memory_info.total
        memory_percent = memory_info.percent

        # 获取CPU占比前三的进程
        cpu_top_processes = sorted(
            [(p.name(), p.cpu_percent()) for p in psutil.process_iter(attrs=['name', 'cpu_percent'])],
            key=lambda x: x[1],
            reverse=True
        )[:5]

        # 获取内存占比前三的进程
        memory_top_processes = sorted(
            [(p.name(), p.memory_percent()) for p in psutil.process_iter(attrs=['name', 'memory_percent'])],
            key=lambda x: x[1],
            reverse=True
        )[:3]
        net_io = psutil.net_io_counters()

        data = {
            "cpu_core": cpu_count,
            "cpu_usage": cpu_percent,
            "memory_total": total_memory,
            "memory_usage": memory_percent,
            "net_up": net_io.bytes_sent,
            "net_down": net_io.bytes_recv,
            "top_processes": {
                "cpu": cpu_top_processes,
                "memory": memory_top_processes
            },
            "cpu_info": get_cpu_brand(),
        }
        return jsonify(data)
    elif path == "get/system_info":
        data = {
            "code": 200,
            "data": System.get_system_name_all()
        }
        return jsonify(data)
    elif path == "get/restart_system":
        System.restar_system()
        return jsonify({'code': 200, 'msg': 'System restarting'})

    elif path == "get/off_system":
        System.off_system()
        return jsonify({'code': 200, 'msg': 'System restarting'})
    elif path == "post/set_port":
        data = data.decode('utf-8')
        data = json.loads(data)
        System.set_firewall_rule(port=int(data["port"]), system=System.get_system_name(), status=data["status"],
                                 protocol=data["protocol"], source_ip=data["source_ip"])
        return jsonify({'code': 200, 'msg': 'Port set successfully'})
    elif path == "get/port_rules":
        data = System.get_firewall_rules(System.get_system_name())
        if json.loads(data):
            if System.get_system_name() == "Windows":
                system_type = "win"
            else:
                system_type = "linux"
            return jsonify({"code": 200, "data": json.loads(data), "type": system_type})
        else:
            return jsonify({"code": 404, "data": "No rules found"})
    elif path == "post/get_file_data":
        data = request.get_json()
        data = File.get_directory_tree(data["path"])
        return jsonify({"code": 200, "data": data})